module PdbRoutine

using PdbParser
using DataFrames
using CSV
using Utils

function pdb_functions(pdb, pdbfilename::String)
    while true
        println(h("\n                    ************ PDB functions ************", fc="c"))
        println(" 0 Return")
        println(" 1 Generate pdb from csv file")
        println(" 2 Output to pdb file")
        input = sel_fun(Int32)
        if input == 0
            return
        elseif input == 1
            csv2pdb()
        elseif input == 2
            generate_pdb(pdb, pdbfilename)
        end
    end
end

function csv2pdb()
    # TODO: 将这个功能换个位置
    request_hint("\nInput csv file path or \"q\" to return.\n")
    println("The input csv file was usually generated by other visualization softwares
such as Discovery Studio. It should contain the following data:
===================================================================================
atom type | atom id | atom name | residue | chain | resid |     x |      y |      z
-----------------------------------------------------------------------------------
     ATOM |       1 |         N |     HIS |     A |     1 | 6.212 | 66.712 | 49.718  (csv data example)
     ATOM | ...
===================================================================================
", h("NOTE: ", fc="y"), "The csv file should not contain the head line.
", h("NOTE2: ", fc="y"), "Currently only support one model.")
    csv_file = readline()
    if csv_file == "q"
        return
    end
    data = CSV.read(csv_file, DataFrame, header=0)
    items = Vector{AbstractPdbCoordinate}()
    for item in eachrow(data)
        if item[1] == "ATOM"
            push!(items, PdbAtom("ATOM", item[2], "$(item[3])", ' ', item[4], item[5][1], item[6], ' ', 
            item[7], item[8], item[9], 0, 0, "$(item[3][1])", ""))
        elseif item[1] == "TER"
            push!(items, PdbTer("TER", item[2], item[3], item[4][1], parse(Int32, item[5]), ' '))
        end
    end
    pdb = PDB("Created from csv file: $csv_file", [0, 0, 0], [PdbModel(1, items)], [])
    generate_pdb(pdb, csv_file[1:end-4] * ".pdb")
end

function generate_pdb(pdb::PDB, pdbfilename::AbstractString)
    new_file = get_path(pdbfilename)
    to_pdb(pdb, new_file)
    finish_path(new_file)
end

end